package com.epoint.mobileoa.ui.mail;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Html;
import android.text.Spanned;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.SuperView;
import com.epoint.mobileoa.bizlogic.Task;
import com.epoint.mobileoa.bizlogic.mobileoa.GetMailSignInfoTask;
import com.epoint.mobileoa.bizlogic.mobileoa.GetSendMailListTask;
import com.epoint.mobileoa.datanalysis.XMLHelp;
import com.epoint.mobileoa.model.MailSendFromServiceModel;
import com.epoint.mobileoa.model.MailSign;
import com.epoint.mobileoa.service.MainService;
import com.epoint.mobileoa.tools.AlertHelp;
import com.epoint.mobileoa.tools.DateHelp;
import com.epoint.mobileoa.tools.EpointDialog;
import com.epoint.mobileoa.tools.PropertiesHelp;
import com.epoint.mobileoa.tools.StringHelp;
import com.epoint.mobileoa.tools.ToastHelp;
import com.epoint.mobileoa.tools.XMLUtil;

/**
 * @author liyc
 * @time 2012-2-7 下午9:36:56
 * @annotation 发件箱
 */
public class MailBoxSendView extends SuperView{

	private int tasktype;//0获取邮件列表，1获取签收情况

	public static final int GetSendMailList = 1;

	private ListView lv;

	private int shownum = 20;//每页显示数量

	private int pagenum = 1;//第几页

	public static int allmailnums;//所有邮件数量

	//	private Button load_bt;//加载中的文本
	private LinearLayout foot;

	//加载的所有邮件
	private List<MailSendFromServiceModel> alllist = new ArrayList<MailSendFromServiceModel>();

	private MyAdapter adapter = new MyAdapter();

	//查询条件
	private String sjFrom = "",sjTo = "",bt = "",sjr = "";
	@Override
	public void initControls() {
		lv = (ListView) findViewById(R.id.lv_mailstyle);
		lv.setOnItemClickListener(this);
//		lv.setOnItemLongClickListener(this);
		//查询按钮
		if("1".equals(PropertiesHelp.getProperty(this,"MainSearch"))){
			//			top_right_bt.setBackgroundResource(R.drawable.top_right_search);
			top_right_bt.setText("查找");
			top_right_bt.setVisibility(View.VISIBLE);
			top_right_bt.setOnClickListener(this);
		}

		addFoot();

		lv.setAdapter(adapter);

		getData(pagenum,shownum);

		lv.setVisibility(View.INVISIBLE);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		final int mPosition = position;
		if(position!=alllist.size()){
			AlertHelp.showAlertMenu(this, "选项", new String[]{"查看签收情况"}, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					if(which==0)
					{
						System.out.println(alllist.get(mPosition).guid);
						top_pb.setVisibility(View.VISIBLE);
						HashMap<String,Object> param= new HashMap<String,Object>();
						param.put("outmailguid", alllist.get(mPosition).guid);
						tasktype = 1;
						Task task = new GetMailSignInfoTask(MailBoxSendView.this, param);
						MainService.addTask(task);
					}
				}

			});
		}
		return super.onItemLongClick(parent, view, mPosition, id);
	}

	public void getData(int pagenum, int shownum){
		top_pb.setVisibility(View.VISIBLE);
		HashMap<String,Object> param= new HashMap<String,Object>();
		param.put("pagenum", pagenum);
		param.put("shownum", shownum);
		param.put("sjfrom", sjFrom);
		param.put("sjto", sjTo);
		param.put("bt", bt);
		param.put("sjr", sjr);
		tasktype = 0;
		Task task = new GetSendMailListTask(this, param);
		MainService.addTask(task);
	}

	public void addFoot(){
		TextView load_bt = new TextView(this);
		load_bt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
		load_bt.setText("更多...");
		load_bt.setGravity(Gravity.CENTER);
		foot = new LinearLayout(this);
		foot.addView(load_bt, new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT));
		foot.setGravity(Gravity.CENTER);
		lv.addFooterView(foot);
		registerForContextMenu(lv);
	}

	@Override
	public void refresh(Object... param) {
		top_pb.setVisibility(View.INVISIBLE);

		if(param[0].toString().equals(MainService.NORMAL)){
			if(tasktype==0){
				lv.setVisibility(View.VISIBLE);

				String bs = param[1].toString();
				allmailnums = Integer.parseInt(StringHelp.getXMLAtt(bs, "allnum"));
				String content =  "<root>"+StringHelp.getXMLAtt(bs, "getmails")+"</root>";
				List<MailSendFromServiceModel> maillist = XMLHelp.AnalysisSendEmailListXML(content);

				if(maillist.size()==0){
					ToastHelp.showToastCommon(this, "数据加载完毕");
				}

				if(pagenum==1){
					alllist.clear();
				}

				for(MailSendFromServiceModel m:maillist){
					alllist.add(m);
				}

				adapter.notifyDataSetChanged();
			}
			else if(tasktype==1)
			{
				try{
					String xml = param[1].toString();
					List<MailSign> mslist = XMLUtil.DomAnalysisCommon(xml, MailSign.class);

					StringBuilder sb = new StringBuilder();
					for(int i=0;i<mslist.size();i++)
					{
						MailSign ms=mslist.get(i);
						sb.append(ms.displayname+"<font color=red>("+(ms.haveread.equals("1")?"已签收":"未签收")+")</font>");
						if(i!=mslist.size()-1)
						{
							sb.append("<br/>");
						}
					}

					epointDialog = EpointDialog.getDialog(
							this, 
							sb.toString(), 
							3, 
							new View.OnClickListener() {
								@Override
								public void onClick(View v) {
									epointDialog.dismiss();
								}
							});
					epointDialog.show();
				}catch(Exception e)
				{
					e.printStackTrace();
					Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	@Override
	public int getLayoutInt() {
		return R.layout.layout_mailstyle;
	}

	@Override
	public String setTitle() {
		return "发件箱";
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		if(position==alllist.size()){
			pagenum ++;
			getData(pagenum, shownum);
			return;
		}
		Intent it = new Intent(this,MailDetailView.class);
		it.putExtra("pagetitle", "邮件详情");
		it.putExtra("mailtitle", alllist.get(position).title);
		it.putExtra("mailguid", alllist.get(position).guid);
		it.putExtra("mailsender",fp.getDisplayname());
		it.putExtra("mailtime", alllist.get(position).time);
		it.putExtra("hasattach", alllist.get(position).hasattach);
		MailDetailView.pagetype = 0;
		startActivity(it);
	}

	@Override
	public void onClick(View v) {
		if(v==top_right_bt){

			LayoutInflater inflater = LayoutInflater
					.from(this);
			LinearLayout ll = (LinearLayout) inflater.inflate(
					R.layout.mailsearchlayout, null);

			final EditText etSjFrom = (EditText) ll.findViewById(R.id.etSjFrom);
			final EditText etSjTo = (EditText) ll.findViewById(R.id.etSjTo);
			final EditText etTitle = (EditText) ll.findViewById(R.id.etTitle);
			final EditText etSjr = (EditText) ll.findViewById(R.id.etSjr);

			etSjFrom.setText(sjFrom);
			etSjTo.setText(sjTo);
			etTitle.setText(bt);
			etSjr.setText(sjr);
			etSjr.setHint("请输入收件人");
			etSjFrom.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					AlertHelp.showDatePickDialogWithCancel(MailBoxSendView.this, new OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear,
								int dayOfMonth) {
							etSjFrom.setText(year + "-" + DateHelp.switchDay((monthOfYear+1)) + "-" + DateHelp.switchDay(dayOfMonth));
						}
					},null);
				}
			});

			etSjTo.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					AlertHelp.showDatePickDialog(MailBoxSendView.this, new OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear,
								int dayOfMonth) {
							etSjTo.setText(year + "-" + DateHelp.switchDay((monthOfYear+1)) + "-" + DateHelp.switchDay(dayOfMonth));
						}
					},null);
				}
			});

			new AlertDialog.Builder(this)
			.setIcon(R.drawable.epoint2)
			.setTitle("发件箱搜索")
			.setView(ll)
			.setPositiveButton("确定",new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					sjFrom = etSjFrom.getText().toString();
					sjTo = etSjTo.getText().toString();
					bt = etTitle.getText().toString();
					sjr = etSjr.getText().toString();

					pagenum = 1;

					getData(pagenum, shownum);
				}
			})
			.setNegativeButton("取消", null)
			.create()
			.show();

		}
	}

	class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return alllist.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			LayoutInflater mInflater = LayoutInflater.from(MailBoxSendView.this);
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.maillist, null);
				holder.ml_mailimg = (ImageView) convertView
						.findViewById(R.id.ml_mailimg);
				holder.ml_attach = (ImageView) convertView
						.findViewById(R.id.ml_attach);
				holder.ml_mailtitle = (TextView) convertView
						.findViewById(R.id.ml_mailtitle);
				holder.ml_sandt = (TextView) convertView
						.findViewById(R.id.ml_sandt);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			//设置是否已经被收件人打开图标
			if("0".equals(alllist.get(position).status)){
				holder.ml_mailimg.setBackgroundResource(R.drawable.view_folder_unread);
			}
			else{
				holder.ml_mailimg.setBackgroundResource(R.drawable.mailopen2);
			}

			//设置是否有附件图标
			if("1".equals(alllist.get(position).hasattach)){
				holder.ml_attach.setVisibility(View.VISIBLE);
				holder.ml_attach.setBackgroundResource(R.drawable.mailattach2);
			}
			else{
				holder.ml_attach.setVisibility(View.GONE);
			}

			holder.ml_mailtitle.setText(alllist.get(position).title);
			setTextViewFontColor(holder.ml_mailtitle);
			String time = alllist.get(position).time;
			Spanned h = Html.fromHtml("<font color="+getYGColor()+">" + time
					+ "</font>");
			holder.ml_sandt.setText(h);
			return convertView;
		}
	}

	public class ViewHolder {
		public ImageView ml_mailimg;
		public ImageView ml_attach;
		public TextView ml_mailtitle;
		public TextView ml_sandt;
	}

	@Override
	public void refreshForNewTask(int TaskId,Object... param) {
	}
}
